package de.lulusoft.anothertorrent.gui.views.Providers;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;

import de.lulusoft.anothertorrent.core.rtorrent.Torrent;
import de.lulusoft.anothertorrent.core.rtorrent.TorrentArrayList;
import de.lulusoft.anothertorrent.core.rtorrent.View;

public class TorrentListViewContentProvider implements PropertyChangeListener,
	IStructuredContentProvider{
	
	private TableViewer viewer;

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

		this.viewer = (TableViewer) viewer;
		if (oldInput instanceof View)
		{
			View view = (View)oldInput;
			view.removeListener(this);
		}
		if (newInput instanceof View)
		{
			View view = (View)newInput;
			view.addListener(this);
		}
		viewer.refresh();
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof View)
		{
			return ((View)inputElement).getTorrents().toArray();
		}
		else if (inputElement instanceof Torrent)
		{
			return null;
		}
		return null;
	}
	
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		TorrentArrayList changedTorrents = (TorrentArrayList)evt.getNewValue();
		if (evt.getPropertyName().equals(View.PROP_NAME))
		{
			// Should not happen...
		}
		else if (evt.getPropertyName().equals(View.PROP_NEW))
		{
			viewer.add(changedTorrents.toArray());
//			System.out.println(View.PROP_NEW + ": " + changedTorrents.size());
		}
		else if (evt.getPropertyName().equals(View.PROP_UPDATED))
		{
			viewer.update(changedTorrents.toArray(), null);
//			System.out.println(View.PROP_UPDATED + ": " + changedTorrents.size());
		}
		else if (evt.getPropertyName().equals(View.PROP_REMOVED))
		{
			viewer.remove(changedTorrents.toArray());
			System.out.println(View.PROP_REMOVED + ": " + changedTorrents.size());
		}
	}

}
